import 'package:flutter/material.dart';
import 'dart:async';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:flutter_channel_demo/utils/tools.dart';

class WebviewPage extends StatefulWidget {
  Map arguments;

  WebviewPage({super.key, required this.arguments});

  @override
  State<WebviewPage> createState() => _WebviewPageState();
}

class _WebviewPageState extends State<WebviewPage> {
  WebViewController? _webviewController;
  late final String _title;
  Future<bool> _exitApp(BuildContext context) async {
    if (await _webviewController!.canGoBack()) {
      debugPrint("onWill goBack");
      _webviewController!.goBack();
      return Future.value(false);
    } else {
      debugPrint("_exit will not go back");
      return Future.value(true);
    }
  }

  @override
  void initState() {
    setState(() {
      _title = widget.arguments["title"] ?? 'webview';
    });

    super.initState();
  }

  // void _navigatePage(
  //   BuildContext context,
  //   String uri,
  // ) {
  //   switch (uri) {
  //     case '/person':
  //     case '/contracts':
  //     case '/home':
  //       switchTab(context, uri);
  //       break;
  //     default:
  //       Navigator.pushNamed(context, uri);
  //   }
  // }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        child: Scaffold(
          appBar: AppBar(title: Text(_title)),
          body: WebView(
            initialUrl: widget.arguments['url'],
            javascriptMode: JavascriptMode.unrestricted,
            onWebViewCreated: (WebViewController webViewController) {
              _webviewController = webViewController;
            },
            navigationDelegate: (NavigationRequest request) {
              if (request.url.indexOf(".ess.tencent.cn/m/") > -1) {
                debugPrint("即将打开 ${request.url}");
                switchTab(context, '/contracts');
                return NavigationDecision.prevent;
              }
              return NavigationDecision.navigate;
            },
          ),
        ),
        onWillPop: () => _exitApp(context));
  }
}
